<template>
  <div ref="container" class="goodsinfo-container">
    <SearchInput
      @onSearch="onSearch"
      v-model="word"
      showBack
      :style="{ opacity: opacity }"
      v-show="opacity > 0.65"
    />
    <GoodsSwiper :imgs="imgs.map(i => ({ title: info.g_name, src: i }))" />
    <div class="wrapper">
      <div class="price">
        ￥<strong>{{ price }}</strong>
      </div>
      <div class="buynum">销量：{{ buynum }}</div>
      <div class="goods_name">{{ info.g_name }}</div>
    </div>
    <div class="wrapper">
      <van-cell
        v-if="info.specs"
        @click="info.specs.length && openGoodsSpecsPop(true, 'all')"
        :value="info.specs.length === 0 ? '暂无库存' : null"
        is-link
        title="选择规格"
      />
      <van-cell title="商品分类" :value="info.category_name" />
      <van-cell title="上市时间" :value="info.create_time" />
    </div>
    <nuxt-link
      :to="{ name: 'store-id', params: { id: info.b_id } }"
      class="wrapper store"
    >
      <img :src="info.b_src | formatSrc" :alt="info.b_name" />
      <div class="info text-over">{{ info.b_name }}</div>
      <div class="comment">
        <p>店铺评分：5.0分</p>
        <p>店铺评分：5.0分</p>
        <p>店铺评分：5.0分</p>
      </div>
    </nuxt-link>
    <van-goods-action class="bottom">
      <van-goods-action-icon
        icon="shop-o"
        @click.stop="
          $router.push({ name: 'store-id', params: { id: info.b_id } })
        "
        text="店铺"
      />
      <van-goods-action-icon
        icon="cart-o"
        @click.stop="$router.push({ name: 'cart' })"
        text="购物车"
      />
      <van-goods-action-icon
        :color="info.isLike ? '#ff5000' : '#000'"
        :icon="info.isLike ? 'star' : 'star-o'"
        :text="(info.isLike ? '已' : '') + '收藏'"
        @click="clickLike"
      />
      <template v-if="info.specs && info.specs.length !== 0">
        <van-goods-action-button
          type="warning"
          @click="openGoodsSpecsPop(true, 'cart')"
          text="加入购物车"
        />
        <van-goods-action-button
          type="danger"
          text="立即购买"
          @click="openGoodsSpecsPop(true, 'buy')"
        />
      </template>
      <template v-if="info.specs && info.specs.length === 0">
        <van-goods-action-button type="danger" text="暂无商品库存" disabled />
      </template>
    </van-goods-action>
    <div class="desc" v-html="info.g_desc"></div>
    <GoodsSpecsPop
      v-model="showSpecs"
      :specs="info.specs"
      :goodsName="info.g_name"
      :img="imgs[0] | formatSrc"
      :type="showSpecsType"
      @goOrder="goOrder"
    />
  </div>
</template>
<script>
export default {
  layout: "notabbar",
  async asyncData({ error, app, params }) {
    const g_id = params.id;
    try {
      const { status, data } = await app.$apiGetGoodsInfo({ g_id });
      if (status !== 0 || !data) {
        return error({ statusCode: 404 });
      }
      return { info: data };
    } catch (error) {}
  },
  data: () => ({
    info: {}, // 商品信息
    opacity: 0, // 顶部搜索框透明度
    showSpecs: false, // 显示 规格弹窗
    showSpecsType: "all", // 显示弹窗的类型
    word: null
  }),
  methods: {
    // 搜索自动跳转搜索页
    onSearch(word) {
      this.$router.push({
        name: "search",
        query: {
          word
        }
      });
    },
    // 设置搜索框透明度
    containerScroll(e) {
      const top = this.$refs["container"].scrollTop;
      const opacity = top / 300;
      if (opacity <= 1.5) {
        this.opacity = opacity;
      }
    },
    openGoodsSpecsPop(isShow, type) {
      this.showSpecs = isShow;
      this.showSpecsType = type;
    },
    // 跳转 订单页面
    goOrder(data) {
      const goodsInfo = { ...this.info, ...data };
      this.$router.push({
        name: "order-stay",
        params: { type: "goods", goodsInfo }
      });
    },
    // 点击 收藏
    clickLike() {
      const fn = this.info.isLike ? this.$apiDelLike : this.$apiAddLike;
      const { g_id } = this.info;
      fn({ g_id }).then(res => {
        if (res.status === 0) {
          this.$toast({ message: res.msg });
          this.info.isLike = res.data;
        }
      });
    }
  },
  computed: {
    // 图片轮播数组
    imgs() {
      if (!this.info.g_src) {
        return [];
      }
      return this.info.g_src.split(",");
    },
    // 购买人数
    buynum() {
      if (!this.info.specs || !Array.isArray(this.info.specs)) {
        return 0;
      }
      return this.info.specs.reduce((a, c) => a + c.buy_num, 0);
    },
    // 显示价格
    price() {
      if (!this.info.specs || !Array.isArray(this.info.specs)) {
        return 0;
      }
      let price = [],
        discountedPrice = [];
      this.info.specs.forEach(s => {
        if (s.discounted_price) {
          discountedPrice.push(s.discounted_price);
        } else {
          price.push(s.sell_price);
        }
      });
      const all = price.concat(discountedPrice);
      if (all.length === 0) {
        return this.info.discounted_price || this.info.sell_price;
      }
      if (all.length === 1) {
        return all[0];
      }
      all.sort((a, b) => a - b);
      if (all[0] === all[all.length - 1]) {
        return all[0];
      }
      return `${all[0]}~${all[all.length - 1]}`;
    }
  },
  mounted() {
    // 监听滚动
    this.$nextTick(() => {
      this.$refs["container"].addEventListener("scroll", this.containerScroll);
    });
  },
  // 卸载解除 监听
  beforeDestroy() {
    this.$refs["container"].removeEventListener("scroll", this.containerScroll);
  }
};
</script>
<style lang="scss" scoped>
.goodsinfo-container {
  padding-bottom: 50px;
  background: #f1f1f1;
  font-size: 16px;
  overflow-y: auto;
  height: 100vh;
  box-sizing: border-box;
  ::v-deep .search-input {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 2;
    opacity: 0;
  }
  .wrapper {
    padding: 10px;
    margin: 10px;
    background: #fff;
    border-radius: 10px;
    ::v-deep .van-cell {
      padding: 5px 0;
      &::after {
        border: 0;
      }
    }
  }
  .price {
    color: red;
    strong {
      font-size: 20px;
    }
  }
  .goods_name {
    font-weight: 600;
  }
  .buynum {
    display: flex;
    justify-content: flex-end;
    color: #d6d6d6;
    font-size: 14px;
  }
  .store {
    display: flex;
    align-items: flex-start;
    background: #ff6387;
    color: #fff;
    img {
      width: 50px;
      height: auto;
      border-radius: 15px;
      margin-right: 20px;
    }
    p {
      margin: 0;
    }
    .comment {
      float: right;
      font-size: 12px;
    }
    .info {
      width: 150px;
    }
  }
  .desc {
    font-size: 0;
    img {
      display: block;
    }
  }
}
</style>
